<template>
  <view class="todo-list">
    <!-- 卡片列表 -->
    <view class="card-list">
      <view v-for="(section, type) in todoSections" :key="type" class="todo-card">
        <view class="card-header">
          <view class="header-left">
            <text class="section-icon" :class="'icon-' + type"></text>
            <text class="section-title">{{ section.title }}</text>
          </view>
          <view class="header-right" @tap="viewMore(type)">
            <text v-if="pendingCountMap[type]" class="pending-badge">{{ pendingCountMap[type] }}</text>
            <text class="more-text">更多</text>
          </view>
        </view>
        
        <view class="card-content">
          <view v-if="section.items.length === 0" class="empty-tip">
            <text>暂无{{ section.title }}</text>
          </view>
          <template v-else>
            <view 
              v-for="(item, index) in section.items.slice(0, 3)" 
              :key="index"
              class="todo-item"
              :class="{'completed': item.readStatus === 1}"
              @tap="goToDetail(item)"
            >
              <view class="priority-line" :class="'type-' + type"></view>
              <view class="item-content">
                <view class="item-left">
                  <text class="item-title">{{ item.eventName || item.messageTitle }}</text>
                </view>
                <view class="item-right">
                  <text class="item-date" :class="getTimeClass(item.noticeTime)">{{ formatTimeRemaining(item.noticeTime) }}</text>
                  <view class="checkbox" :class="{ 'checked': item.readStatus === 1 }" @tap.stop="toggleComplete(type, index, item)">
                    <text v-if="item.readStatus === 1" class="checkbox-icon">✓</text>
                  </view>
                </view>
              </view>
            </view>
          </template>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, defineExpose } from 'vue'
import MessageApi from '@/sheep/api/message/message'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  styles: {
    type: Object,
    default: () => ({})
  }
});

// 业务类型映射
const businessTypeMap = {
  'IMPORT_DAY': 'anniversary',
  'CONTACT_EVENT': 'task',
  'CUSTOM': 'custom'
}

// 初始化待办分类
const todoSections = ref({
  anniversary: {
    title: '纪念日',
    items: [],
    displayItems: []
  },
  task: {
    title: '重要事项',
    items: [],
    displayItems: []
  },
  custom: {
    title: '自定义',
    items: [],
    displayItems: []
  }
});

const pendingCountMap = ref({
  anniversary: 0,
  task: 0,
  custom: 0
})

// 初始化显示项目
onMounted(() => {
  fetchTodoList();
  fetchPendingCounts();
});

// 获取待办列表数据
const fetchTodoList = async () => {
  try {
    const res = await MessageApi.queryRecentMessage();
    if (res.code === 0 && res.data) {
      // 清空现有数据
      Object.keys(todoSections.value).forEach(type => {
        todoSections.value[type].items = [];
      });
      
      // 处理返回的数据
      res.data.forEach(group => {
        const type = businessTypeMap[group.businessType] || 'custom';
        if (group.messageList && group.messageList.length > 0) {
          todoSections.value[type].items = group.messageList;
        }
      });
    }
  } catch (error) {
    console.error('获取待办列表失败', error);
  }
};

const fetchPendingCounts = async () => {
  try {
    const res = await MessageApi.queryUnReadNoticeNum()
    if (res.code === 0) {
      const typeMap = {
        anniversary: 'IMPORT_DAY',
        task: 'CONTACT_EVENT',
        custom: 'CUSTOM'
      }
      Object.keys(typeMap).forEach(key => {
        const found = res.data.find(item => item.businessType === typeMap[key])
        pendingCountMap.value[key] = found ? found.unreadcount : 0
      })
    }
  } catch (e) {
    console.error('获取未读消息数失败', e)
  }
}

// 查看更多待办
const viewMore = (type) => {
  uni.switchTab({
    url: '/pages/index/message'
  })
}

// 添加完成状态切换方法
const toggleComplete = async (type, index, item) => {
  try {
    // 调用阅读消息接口
    await MessageApi.readNotice({ id: item.id });
    
    // 更新本地状态
    const itemIndex = todoSections.value[type].items.findIndex(i => i.id === item.id);
    if (itemIndex > -1) {
      // 直接移除已读消息
      todoSections.value[type].items.splice(itemIndex, 1);
    }
  } catch (error) {
    console.error('标记已读失败', error);
  }
};

// 格式化剩余时间
const formatTimeRemaining = (timestamp) => {
  if (!timestamp) return '';
  
  const now = Date.now();
  const noticeTime = Number(timestamp);
  const diffMs = noticeTime - now;
  const isExpired = diffMs < 0;
  const absDiffMs = Math.abs(diffMs);
  
  // 转换为分钟、小时、天
  const minutes = Math.floor(absDiffMs / (1000 * 60));
  const hours = Math.floor(absDiffMs / (1000 * 60 * 60));
  const days = Math.floor(absDiffMs / (1000 * 60 * 60 * 24));
  
  if (isExpired) {
    // 已过期
    if (minutes < 60) return `过期${minutes}分钟`;
    if (hours < 24) return `过期${hours}小时`;
    return `过期${days}天`;
  } else {
    // 未过期
    if (minutes < 60) return `剩余${minutes}分钟`;
    if (hours < 24) return `剩余${hours}小时`;
    return `剩余${days}天`;
  }
};

// 获取时间样式类
const getTimeClass = (timestamp) => {
  if (!timestamp) return '';
  
  const now = Date.now();
  const noticeTime = Number(timestamp);
  
  return noticeTime < now ? 'date-overdue' : 'date-future';
};

// 跳转到详情页
const goToDetail = (item) => {
  if (!item.actionUrl) return
  
  // 根据actionUrl进行跳转
  if (item.actionUrl.startsWith('http')) {
    // 使用web-view打开外部链接
    uni.navigateTo({
      url: `/pages/webview/index?url=${encodeURIComponent(item.actionUrl)}`
    })
  } else {
    // 内部页面跳转
    uni.navigateTo({
      url: item.actionUrl
    })
  }
}

// 下拉刷新方法
const onPullDownRefresh = async () => {
  await fetchTodoList();
  await fetchPendingCounts();
  uni.stopPullDownRefresh();
}

// 暴露方法给父页面调用
defineExpose({ onPullDownRefresh })
</script>

<style lang="scss" scoped>
.todo-list {
  background: #f8f8f8;
  padding: 20rpx;
}

.card-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.todo-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 1px solid #f5f5f5;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8rpx;
  
  .more-text {
    &::after {
      content: '›';
      margin-left: 4rpx;
      font-size: 28rpx;
    }
  }
}

.more-text {
  font-size: 24rpx;
  color: #999;
}

.pending-badge {
  background: #ff4d4f;
  color: #fff;
  font-size: 20rpx;
  padding: 2rpx 10rpx;
  border-radius: 20rpx;
  min-width: 28rpx;
  height: 28rpx;
  line-height: 28rpx;
  text-align: center;
}

.card-content {
  .empty-tip {
    text-align: center;
    color: #999;
    font-size: 26rpx;
    padding: 30rpx 0;
  }
}

.todo-item {
  position: relative;
  display: flex;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.priority-line {
  width: 8rpx;
  height: 40rpx;
  border-radius: 4rpx;
  margin-right: 16rpx;
  align-self: center;
  
  // 修改为根据业务类型展示颜色
  &.type-anniversary {
    background: linear-gradient(to bottom, #1677ff, #69c0ff);
  }
  
  &.type-task {
    background: linear-gradient(to bottom, #ff7a45, #ffd591);
  }
  
  &.type-custom {
    background: linear-gradient(to bottom, #52c41a, #95de64);
  }
}

.item-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.item-right {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8rpx;
  
  .more-text {
    &::after {
      content: '›';
      margin-left: 4rpx;
      font-size: 28rpx;
    }
  }
}

.item-date {
  font-size: 24rpx;
  
  &.date-overdue {
    color: #ff4d4f;  // 过期时间显示红色
  }
  
  &.date-future {
    color: #52c41a;  // 未过期时间显示绿色
  }
}

// 保留原有的 checkbox 样式
.checkbox {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  flex-shrink: 0;
  
  &.checked {
    background: #1677ff;
    border-color: #1677ff;
  }
  
  .checkbox-icon {
    color: #fff;
    font-size: 24rpx;
    font-weight: bold;
  }
}

// 保留原有的图标样式
.section-icon {
  width: 36rpx;
  height: 36rpx;
  
  &.icon-anniversary::before {
    content: '🎂';
  }
  
  &.icon-task::before {
    content: '📝';
  }
  
  &.icon-custom::before {
    content: '⭐';
  }
}
</style>